import 'package:bot_toast/bot_toast.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_wallpaper_manager/flutter_wallpaper_manager.dart';
import 'package:path_provider/path_provider.dart';
import 'package:wallpaper/api/mohu.dart';

class Wallpaper extends StatefulWidget {
  const Wallpaper({super.key});

  @override
  State<Wallpaper> createState() => _WallpaperState();
}

class _WallpaperState extends State<Wallpaper>
    with AutomaticKeepAliveClientMixin {
  List images = [];
  List wallpapers = [];
  void getWallpaper() async {
    if (!mounted) return;
    Response res = await mohuImgsApi(id: 'sjpic');
    if (res.data['code'] == '200') {
      setState(() {
        for (var item in res.data['pic']) {
          images.add(item);
        }
      });
    }
  }

  @override
  void initState() {
    getWallpaper();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      body: Padding(
        padding: const EdgeInsets.all(8.0),
        child: GridView.builder(
          gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 2,
            crossAxisSpacing: 10,
            mainAxisSpacing: 10,
            childAspectRatio: 0.5,
          ),
          itemBuilder: (context, index) {
            return Container(
              color: Colors.white,
              child: Column(children: [
                Expanded(
                    child: Image.network(images[index], fit: BoxFit.cover)),
                IconButton(
                  onPressed: () async {
                    var path = await downloadImage(images[index]);
                    print(path);
                    int location =
                        WallpaperManager.BOTH_SCREEN; //can be Home/Lock Screen
                    bool result = await WallpaperManager.setWallpaperFromFile(
                        path!, location);
                    if (result) {
                      BotToast.showText(text: '设置成功');
                    }
                  },
                  icon: Icon(Icons.settings_cell),
                )
              ]),
            );
          },
          itemCount: images.length,
        ),
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}

Future<String?> downloadImage(String url) async {
  try {
    final dir = await getTemporaryDirectory();
    final filename = url.split('/').last;
    final path = '${dir.path}/$filename';

    final response = await Dio().download(url, path);
    if (response.statusCode == 200) {
      return path;
    }
    return null;
  } catch (e) {
    print('下载失败: $e');
    return null;
  }
}
